<?php

namespace app\common\model\crontab;

use tmcore\base\BaseModel;
use app\common\enum\CrontabEnum;
use tmcore\traits\ModelTrait;
use think\model\concern\SoftDelete;

/**
 * 定时任务模型
 */
class SysCrontab extends BaseModel
{
    use ModelTrait;
    use SoftDelete;

    /**
     * 状态获取器
     * @param $value
     * @return string
     */
    public function getStatusDescAttr($value)
    {
        $desc = [
            CrontabEnum::START => '运行',
            CrontabEnum::STOP => '停止',
            CrontabEnum::ERROR => '错误',
        ];
        return $desc[$value] ?? '';
    }

    /**
     * 运行规则描述
     * @param $value
     * @return string
     */
    public function getExpressionDescAttr($value)
    {

        $expression_params = json_decode($value, true);

        $desc = '';
        $week_arr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

        switch ($expression_params['type']) {
            case 1:
                $desc = '每天'.$expression_params['hour'].'时'.$expression_params['min'].'分执行一次';
                break;
            case 2:
                $desc = '每'.$expression_params['day'].'天的'.$expression_params['hour'].'时'.$expression_params['min'].'分执行一次';
                break;
            case 3:
                $desc = '每小时的'.$expression_params['min'].'分执行一次';
                break;
            case 4:
                $desc = '每'.$expression_params['hour'].'小时的'.$expression_params['min'].'分执行一次';
                break;
            case 5:
                $desc = '每'.$expression_params['min'].'分执行一次';
                break;
            case 6:
                $desc = '每星期'. $week_arr[$expression_params['week'] - 1].'的'.$expression_params['hour'].'时'.$expression_params['min'].'分执行一次';
                break;
            case 7:
                $desc = '每月'. $expression_params['day'].'日的'.$expression_params['hour'].'时'.$expression_params['min'].'分执行一次';
                break;
            case 8:
                $desc = $expression_params['cron'];
                break;
        }

        return $desc;
    }

    /**
     * 运行规则参数获取器
     * @param $value
     * @return string
     */
    public function getExpressionParamsAttr($value)
    {
        return empty($value) ? '' : json_decode($value, true);
    }

    /**
     * 最后执行时间获取器
     * @param $value
     * @return string
     */
    public function getLastTimeAttr($value)
    {
        return empty($value) ? '' : date('Y-m-d H:i:s', $value);
    }
}